# -*- coding:utf-8 -*-
"""Created By Corvo"""

from const import *
from ..mdk.client.entity import *
from ..mdk.module.system.base import *
from ..modCommon.modConfig import ModUI, ModServer, ModEffect, ModMolang
from ..modCommon.modEnum import ModMergeData


class DataMergeModuleClient(ModuleClientBase):
    """数据合并模块客户端"""
    __mVersion__ = 115
    __identifier__ = ModuleEnum.identifier

    def __init__(self):
        super(DataMergeModuleClient, self).__init__()
        self.render_type = set()
        self.ice_render_storage = {}

        self.textures = {
            "ice_model": "textures/entity/beast/ice_model"
        }
        self.geometries = {
            "ice_model": "geometry.beast.ice_model"
        }
        self.scripts = {
            "ice_model_idle": "query.mod.ice_model_effect"
        }
        self.animations = {
            "ice_model_idle": "animation.beast.ice_model.idle"
        }
        self.render_controllers = {
            "controller.render.beast.ice_model": "query.mod.ice_model_effect"
        }
        self.materials = {
            "ice_model": "entity_alphablend"
        }

    def ConfigEvent(self):
        super(DataMergeModuleClient, self).ConfigEvent()
        self.defaultEvent.update({
            ClientEvent.UiInitFinished: self.UiInitFinished,
            ClientEvent.OnScriptTickClient: self.OnScriptTickClient,
        })
        self.clientEvent.update({
            # "UIRequestSwitchStoneWatchEvent": self.UIRequestSwitchStoneWatchEvent,
            # "UIRequestSwitchTriWatchEvent": self.UIRequestSwitchTriWatchEvent,
            "ModuleRequestLoadMolangConfigEvent": self.ModuleRequestLoadMolangConfigEvent,
        })
        self.serverEvent.update({
            ModuleEvent.ModuleRequestUpdateMergeDataEvent: self.ModuleRequestUpdateMergeDataEvent,
            ModServer.OnPlayerUpdateBeastStoneEffectEvent: self.OnPlayerUpdateBeastStoneEffectEvent,
            "RequestRenderIceModelEvent": self.RequestRenderIceModelEvent,
        })

    # -----------------------------------------------------------------------------------

    def BuildIceModeResource(self, target_id, engine_type):
        # type: (str, str) -> None
        """构建冰模型特效渲染资源"""

        # 渲染资源动态导入
        render_comp = self.comp_factory.CreateActorRender(target_id)
        for key, path in self.textures.iteritems():
            path, render_comp.AddActorTexture(engine_type, key, path)
        for key, path in self.geometries.iteritems():
            path, render_comp.AddActorGeometry(engine_type, key, path)
        for key, path in self.animations.iteritems():
            path, render_comp.AddActorAnimation(engine_type, key, path)
        yield 1
        for key, path in self.materials.iteritems():
            path, render_comp.AddActorRenderMaterial(engine_type, key, path)
        for key, condition in self.render_controllers.iteritems():
            if not render_comp.AddActorRenderController(engine_type, key, condition):
                render_comp.RemoveActorRenderController(engine_type, key)
                render_comp.AddActorRenderController(engine_type, key, condition)
        for key, condition in self.scripts.iteritems():
            if not render_comp.AddActorScriptAnimate(engine_type, key, condition):
                render_comp.AddActorScriptAnimate(engine_type, key, condition, True)
        render_comp.RebuildActorRender(engine_type)
        self.render_type.add(engine_type)

    # -----------------------------------------------------------------------------------

    def UiInitFinished(self, _):
        pass

    def OnScriptTickClient(self):
        """Tick更新"""
        for entity_id, cd in self.ice_render_storage.items():
            cd -= 1
            if cd <= 0:
                self.ice_render_storage.pop(entity_id)
                query_comp = self.comp_factory.CreateQueryVariable(entity_id)
                continue
            self.ice_render_storage[entity_id] = cd

    @classmethod
    def ModuleRequestUpdateMergeDataEvent(cls, args):
        for key, value in args["data"].iteritems():
            setattr(ModMergeData, key, value)
        ModMergeData.BookShowEntity = ModMergeData.CaptureEntity + ModMergeData.CombineEntity
        ModMergeData.MachineEntity = ModMergeData.MachineCombine + ModMergeData.MachineSprite

    def OnPlayerUpdateBeastStoneEffectEvent(self, args):
        """"""

    def RequestRenderIceModelEvent(self, args):
        # type: (dict) -> None
        """
        渲染冰模型\n
        - targetId: str
        - duration: float
        - collision: tuple
        """
        target_id = args["targetId"]
        duration = args["duration"]
        collision_x, collision_y = args["collision"]

        def active():
            query_comp = self.comp_factory.CreateQueryVariable(target_id)
            # 设置效果时长
            # query_comp.Set(ModMolang.ice_model_effect, 1.0)
            # scale = max(collision_x, collision_y) / 5
            # query_comp.Set(ModMolang.collision_box_x, scale)
            # query_comp.Set(ModMolang.collision_box_y, scale)
            self.ice_render_storage[target_id] = int(duration * 30)

        engine_type = RawEntity.GetTypeStr(target_id)
        if engine_type in self.render_type:
            active()
        else:
            self.StartCoroutine(self.BuildIceModeResource(target_id, engine_type), active)

    @classmethod
    def ModuleRequestLoadMolangConfigEvent(cls, args):
        molang = args["molang"]  # type: list
        molang.extend(ModMolang.AllMolang)
